package com.stu.covid.business.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.stu.covid.business.entity.StudentHealth;
import com.stu.covid.business.entity.Teacher;
import com.stu.covid.business.mapper.StudentHealthMapper;
import com.stu.covid.business.mapper.TeacherMapper;
import com.stu.covid.business.utils.CodeMsg;
import com.stu.covid.business.utils.Result;
import com.stu.covid.business.utils.ResultFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class StudentHealthService {

    @Autowired
    private StudentHealthMapper studentHealthMapper;

    public Result<StudentHealth> list(StudentHealth studentHealth) {
        List<StudentHealth> list = studentHealthMapper.list(studentHealth);
        Integer count = studentHealthMapper.count(studentHealth);
        return ResultFactory.bulid(CodeMsg.SUCCESS, count, list);
    }

    public void add(StudentHealth studentHealth) {
        studentHealthMapper.insertSelective(studentHealth);
    }

    public void update(StudentHealth studentHealth) {
        studentHealthMapper.updateByPrimaryKeySelective(studentHealth);
    }

    public void del(Integer id) {
        studentHealthMapper.deleteByPrimaryKey(id);
    }

    public void export(HttpServletRequest request, HttpServletResponse response, StudentHealth studentHealth) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            studentHealth.setPage(1);
            studentHealth.setLimit(999999);
            Result<StudentHealth> result = this.list(studentHealth);

            EasyExcel.write(response.getOutputStream(), StudentHealth.class).sheet("sheet").doWrite(result.getData());
        } catch (ExcelDataConvertException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
